import { useEffect, useState } from "react";
import { type TreeSelectProps } from "antd"
import { RespDataType, getRoleParams } from '../api';


interface FormatMenuData {
  pidToChildIdList: { [index: number]: number[] },
  childIdToPid: { [index: number]: number },
}


export const useList = () => {
  const [loading, setLoading] = useState(true);
  const [initData, setInitData] = useState<{
    // menuList: RespDataType.RoleParams["menu"],
    menuTree: TreeSelectProps["treeData"],
    formatMenuData?: FormatMenuData,
  }>({
    menuTree: [],
    formatMenuData: {
      pidToChildIdList: {},
      childIdToPid: {}
    }
  });

  useEffect(() => {
    setLoading(true);
    getRoleParams().then((resp) => {
        // const menuTree = resp.data || [];
        const menuTree = toTree(resp.data.menu) || []
        setInitData({
            menuTree,
            formatMenuData: doFormatMenuData(menuTree),
        })
        setLoading(false);
    })

    setLoading(false);
  }, []);

  return { loading, initData };
}

const doFormatMenuData = (menuTree: TreeSelectProps["treeData"], pidToChildIdList: { [index: number]: number[] } = {}, childIdToPid: { [index: number]: number } = {}) => {
  menuTree.forEach((item) => {
    if (item.children && item.children.length > 0) {
      pidToChildIdList[item.id] = item.children.map((childItem) => childItem.id);
      item.children.forEach((childItem) => {
        childIdToPid[childItem.id] = item.id;
      });
      doFormatMenuData(item.children, pidToChildIdList, childIdToPid)
    }
  })

  return { pidToChildIdList, childIdToPid };
}

/**
 * 将数据转为树状数据结构
 */
const toTree = (dataList: RespDataType.RoleParams["menu"]) => {
  const parentId = Math.min(...dataList.map(item => item.pid));
  const loop = (parentId: number): TreeSelectProps["treeData"] => {
    const res: TreeSelectProps["treeData"] = []
    for (let i = 0; i < dataList.length; i++) {
      const {id, title, pid} = dataList[i]

      if (pid !== parentId) {
        continue
      }
      // item.children = loop(item.deptId)
      res.push({
        label: title,
        id,
        key: id,
        value: id,
        children: loop(id)
      })
    }
    return res.length > 0 ? res : null
  }

  return loop(parentId)
}
